package com.cooper.scraper;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;

public class Exp {

	Exp(String rule, boolean repeat) {
		this.rule = rule;
		this.repeat = repeat;
	}

	public Exp(XmlPullParser xml) {
		repeat = Scraper
				.parseBool(xml.getAttributeValue(null, "repeat"), false);
		String nocleanStr = xml.getAttributeValue(null, "noclean");
		if (nocleanStr != null && !nocleanStr.trim().equals("")) {
			for (String s : nocleanStr.split(",")) {
				noclean.add(Integer.parseInt(s));
			}
		}

		String trimStr = xml.getAttributeValue(null, "trim");
		if (trimStr != null && !trimStr.trim().equals("")) {
			for (String s : trimStr.split(",")) {
				trim.add(Integer.parseInt(s));
			}
		}

		clear = Scraper.parseBool(xml.getAttributeValue(null, "clear"), false);
	}

	public boolean clear = false;
	private boolean repeat = false;
	private List<Integer> noclean = new ArrayList<Integer>();
	private List<Integer> trim = new ArrayList<Integer>();
	private String rule;
	
	public String getRule() {
		return rule;
	}

	public void setRule(String rule) {
		this.rule = rule;
	}

	public String matchExp(String useRule,String input, String output) {
		String result = "";
		List<String> rules = new ArrayList<String>();
		if ((useRule == null) || useRule.trim().equals("")) {
			rules.add(input);
			result = replaceOutput(rules, output);
		} else {
			Pattern p = Pattern.compile(useRule);
			Matcher m = p.matcher(input);
			List<String> regGroups = new ArrayList<String>();
			boolean found = false;
			while (m.find()) {
				found = true;
				regGroups.clear();
				for (int i = 1; i <= m.groupCount(); i++) {
					regGroups.add(m.group(i) == null ? "" : m.group(i));
				}
				result += replaceOutput(regGroups, output);
				if (!repeat)
					break;
			}
			if (!found) {
				return null;
			}
		}
		return result;
	}

	String clean(String str) {
		return str.replaceAll("</{0,1}.*?>", "").replaceAll("&.*?;", "")
				.replace("&", "&amp;").replace("<", "&lt;")
				.replace(">", "&gt;").replace("'", "&apos;")
				.replace("\"", "&quot;").replace("&nbsp", " ");
	}

	private String replaceOutput(List<String> expGroupResults, String output) {
		String result = output;
		
		for (int i = expGroupResults.size() - 1; i >= 0; i--) {
			String egResults = expGroupResults.get(i);
			egResults = egResults == null ? "" : egResults;

			if (!noclean.contains(Integer.valueOf(i + 1))) {
				egResults = clean(egResults);
			}
			if (trim.contains(Integer.valueOf(i + 1))) {
				egResults = egResults.trim();
			}
			result = result.replace("\\" + String.valueOf(i + 1), egResults);
		}
		return result;
	}
}